const express = require("express");
const router = express.Router();
const multer = require('multer');
const path = require("path");



const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.resolve(__dirname, "../blogWeb/upload"))
    },
    filename: function (req, file, cb) {
        // 时间戳+随机的6位数+后缀名
        const time = Date.now();
        const randomStr = Math.random().toString(36).slice(-6);
        const ext = path.extname(file.originalname);
        const filename = `${time}-${randomStr}${ext}`
        cb(null, filename)
    }
})

const upload = multer({
    storage,
    fileFilter(req, file, cb) { //限制文件的格式
        const extname = path.extname(file.originalname); //获取文件后缀名
        const list = [".jpg", ".png", ".gif", ".webp", ".jpeg", ".svg"];
        if (list.includes(extname)) {
            cb(null, true)
        } else {
            cb(new Error(`暂不支持${extname}格式的图片`))
        }
    }
})



router.post('/', upload.single('img'), (req, res) => {
    res.send({
        code: 0,
        msg: "",
        data: `/upload/${req.file.filename}`
    })
})

module.exports = router;